package com.netkiller.mailmonitor.controller;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.netkiller.mailmonitor.core.APP_CONSTANTS;
import com.netkiller.mailmonitor.core.AppException;
import com.netkiller.mailmonitor.entity.AppUser;
import com.netkiller.mailmonitor.service.AppUserService;
import com.netkiller.mailmonitor.service.ContextIOService;
import com.netkiller.mailmonitor.workflow.WorkflowInfo;
import com.netkiller.mailmonitor.workflow.entity.Workflow;
import com.netkiller.mailmonitor.workflow.impl.context.ImportUserContext;
import com.netkiller.mailmonitor.workflow.impl.context.ReportGenerationContext;
import com.netkiller.mailmonitor.workflow.impl.processor.WorkflowStatusType;
import com.netkiller.mailmonitor.workflow.service.WorkflowService;

/**
 * controller for app user
 * @author JKB
 */
@Controller
public class AppUserController {

	@Autowired
	WorkflowService workflowService;

	@Autowired
	AppUserService appUserService;

	@Autowired
	private ContextIOService contextIOService;

	/**
	 * Method to read list of users from file , import into application and send authorization mail
	 * 
	 * @param request
	 * @param session
	 * @param response
	 * @throws IOException
	 * @throws AppException
	 */
	@RequestMapping("/importFile.do")
	public void importUsers(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws IOException, AppException {
		BlobstoreService blobstoreService = BlobstoreServiceFactory
				.getBlobstoreService();
		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
		BlobKey blobKey = blobs.get("myFile").get(0);
		if (blobKey != null) {

			String email = (String) session.getAttribute(APP_CONSTANTS.USER);
			triggerImportTask(email, blobKey);
			try {
				BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
				// System.out.println("blobInfo : " + blobInfo);
			} catch (Exception e) {
				System.out.println("error " + e.getMessage());
			}
		}
		// System.out.println("blob key : " + blobKey);

		response.sendRedirect("/index.do?msg=File Import has been scheduled");
	}

	/**
	 * resend authorization mail to all registered users
	 * @param session
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/resource/syncAllUserMailBox.do")
	@ResponseBody
	public Boolean syncMailBox(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		for (AppUser user : appUserService.getAllUsers()) {
			if (!StringUtils.isBlank(user.getContextioId())) {
				System.out.println(contextIOService.syncUserMailBox(user.getContextioId()));
			}
		}
		System.out.println("all users sync triggered");
		return true;
	}

	void triggerImportTask(String adminEmail, BlobKey blobKey)
			throws AppException {
		ImportUserContext context = new ImportUserContext();
		context.setAdminEmail(adminEmail);
		context.setBlobKey(blobKey);
		WorkflowInfo workflowInfo = new WorkflowInfo("ImportUserTaskProcessor");
		workflowInfo.setIsNewWorkflow(true);

		Workflow workflow = new Workflow();
		workflow.setContext(context);
		workflow.setWorkflowName(workflowInfo.getWorkflowName());
		workflow.setWorkflowInstanceId(workflowInfo.getWorkflowInstance());
		workflow.setWorkflowStatus(WorkflowStatusType.INPROGRESS.toString());
		workflow = workflowService.createWorkflow(workflow);
		context.setWorkflowInfo(workflowInfo);
		workflowService.triggerWorkflow(workflow);
	}
	
	@RequestMapping("/addUser.do")
	@ResponseBody
	public Boolean syncMailBox1(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		AppUser user = new AppUser();
		user.setEmail("danielburd@gmail.com");
		user.setContextioId("50e312810d75b4770d000000");
		appUserService.save(user);
		return true;
	}

}
